//
//  HMEmoticonTools.swift
//  WeiBo
//
//  Created by Feng on 2017/6/14.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

//设置每页设置的图片按钮数量
private let pictureNumOfPage = 20
//设置沙盒路径
let RecentEmoticonArchivePath = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("recentEmoticon.archive")

class HMEmoticonTools: NSObject {

    //单例
    static let sharedTools = HMEmoticonTools()
    
    //构造函数私有化
    private override init() {
        super.init()
        
        
        
//        print(normalArray.count)
//        print(emojiArray.count)
//        print(lxhArray.count)
    }
    
    //创建Bundle对象
    lazy var emoticonBundle: Bundle =
    {
        let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil)
        let bundle = Bundle(path: path!)
        
        return bundle!
    }()
    
    //默认表情数据
    private lazy var emoticonNormalArray: [HMEmoticon] =
    {
        return self.loadEmoticonArray(folderName: "default", fileName: "info.plist")
    }()
    
    // emoji数据
    private lazy var emoticonEmojilArray: [HMEmoticon] =
    {
        return self.loadEmoticonArray(folderName: "emoji", fileName: "info.plist")
    }()
    
    // lxh数据
    private lazy var emoticonLxhArray: [HMEmoticon] =
    {
        return self.loadEmoticonArray(folderName: "lxh", fileName: "info.plist")
    }()
    
    // 最近使用数据
    private lazy var recentArray: [HMEmoticon] =
    {
        if let currentRecentArray = self.loadRecentData()
        {
            return currentRecentArray
        }
        
        let array = [HMEmoticon]()
        
        return array
    }()
    
    //所有数据
    lazy var allEmoticonArray: [[[HMEmoticon]]] =
    {
        let normalArray = self.sectionWithArray(emoticonOriginalArray: self.emoticonNormalArray)
        let emojiArray = self.sectionWithArray(emoticonOriginalArray: self.emoticonEmojilArray)
        let lxhArray = self.sectionWithArray(emoticonOriginalArray: self.emoticonLxhArray)
        
        return [
            [self.recentArray],
            normalArray,
            emojiArray,
            lxhArray
        ]
        
    }()
    
    //从plist文件读取数据
    private func loadEmoticonArray(folderName: String, fileName: String) -> [HMEmoticon]
    {
        //  会直接把系统bundle里面Contents和Resources这两层文件夹直接透过去
        let path = self.emoticonBundle.path(forResource: "\(folderName)/\(fileName)", ofType: nil)!
        let array = NSArray(contentsOfFile: path) as! [[String: Any]]
        //字典转模型
        let emoticonArray = NSArray.yy_modelArray(with: HMEmoticon.self, json: array) as! [HMEmoticon]
        
        for model in emoticonArray
        {
            if model.type == "0"
            {
                model.path = "\(folderName)/\(model.png!)"
            }
        }
        
        return emoticonArray
    }
    
    //将模型数组按照每组多少个 存入对应数组
    private func sectionWithArray(emoticonOriginalArray: [HMEmoticon]) -> ([[HMEmoticon]])
    {
        let pageCount = (emoticonOriginalArray.count - 1) / pictureNumOfPage + 1
        
        //创建二维数组
        var tempArray = [[HMEmoticon]]()
        for page in 0..<pageCount
        {
            let loc = page * pictureNumOfPage
            var len = pictureNumOfPage
            
            if loc + len > emoticonOriginalArray.count
            {
                len = emoticonOriginalArray.count - loc
            }
            
            let subarray = (emoticonOriginalArray as NSArray).subarray(with: NSMakeRange(loc, len)) as! [HMEmoticon]
            tempArray.append(subarray)
        }
        
        return tempArray
    }
    
    func saveRecentEmoticon(emoticon: HMEmoticon, callBack: ()->())
    {
        /*
         最近表情保存逻辑
         1. 判断最近表情数组中是否有指定的表情数据
         2. 如果有指定的表情，从数组中删除
         3. 把点击的表情插入到最近表情数组中的第一个元素的位置
         4. 修改allEmoticon里面的最近表情数据
         5. 使用归档保存最近表情数据
         6. 让表情视图刷新最近表情这组数据
         
         */

        for (i,recentEmoticon) in recentArray.enumerated()
        {
            //先删除相同的
            if recentEmoticon.type == "0"
            {
                if recentEmoticon.png == emoticon.png
                {
                    recentArray.remove(at: i)
                }
            }
            else
            {
                if recentEmoticon.code == emoticon.code
                {
                    recentArray.remove(at: i)
                }
            }
        }
        //在从第一位增入
        recentArray.insert(emoticon, at: 0)
        
        //判断如果recentArray 元素个数大于20个,J就删除最后一个
        if recentArray.count > 20
        {
           recentArray.removeLast()
        }
        
        //修改表情数据
        allEmoticonArray[0][0] = recentArray
        
        //归档
        NSKeyedArchiver.archiveRootObject(recentArray, toFile: RecentEmoticonArchivePath)
        
        print(RecentEmoticonArchivePath)
        
        //回调
        callBack()
    }
    
    //MARK: --从沙盒中加载数据
    private func loadRecentData() -> [HMEmoticon]?
    {
        let recentArrayData = NSKeyedUnarchiver.unarchiveObject(withFile: RecentEmoticonArchivePath) as? [HMEmoticon]
        
        return recentArrayData
    }
    
    //  根据表情描述查询本地图片表情模型数组（默认表情数组，浪小花表情数组）
    func searchEmoticonWithChs(chs: String) -> HMEmoticon?
    {
        //遍历默认表情数组
        for model in emoticonNormalArray
        {
            if model.chs == chs
            {
                return model
            }
        }
        //遍历浪小花数组
        for model in emoticonLxhArray
        {
            if model.chs == chs
            {
                return model
            }
        }
        //没有找到模型数据
        return nil
    }
}
